/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: HibernateDao.java 1205 2010-09-09 15:12:17Z calvinxiu $
 */
package com.qyxx.platform.common.orm.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.springframework.util.Assert;

import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.orm.PropertyFilter.MatchType;
import com.qyxx.platform.common.utils.reflection.ReflectionUtils;

/**
 * 封装SpringSide扩展功能的Hibernat DAO泛型基类.
 * 
 * 扩展功能包括分页查询,按属性过滤条件列表查询.
 * 可在Service层直接使用,也可以扩展泛型DAO子类使用,见两个构造函数的注释.
 * 
 * @param <T> DAO操作的对象类型
 * @param <PK> 主键类型
 * 
 * @author gxj
 */
public class HibernateDao<T, PK extends Serializable> extends SimpleHibernateDao<T, PK> {
	/**
	 * 用于Dao层子类的构造函数.
	 * 通过子类的泛型定义取得对象类型Class.
	 * eg.
	 * public class UserDao extends HibernateDao<User, Long>{
	 * }
	 */
	public HibernateDao() {
		super();
	}

	/**
	 * 用于省略Dao层, Service层直接使用通用HibernateDao的构造函数.
	 * 在构造函数中定义对象类型Class.
	 * eg.
	 * HibernateDao<User, Long> userDao = new HibernateDao<User, Long>(sessionFactory, User.class);
	 */
	public HibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
		super(sessionFactory, entityClass);
	}

	//-- 分页查询函数 --//

	/**
	 * 分页获取全部对象.
	 */
	public Page<T> getAll(final Page<T> page) {
		return findPage(page);
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page 分页参数. 注意不支持其中的orderBy参数.
	 * @param hql hql语句.
	 * @param values 数量可变的查询参数,按顺序绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final Page<T> page, final String hql, final Object... values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}

		setPageParameterToQuery(q, page);

		List result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page 分页参数. 注意不支持其中的orderBy参数.
	 * @param hql hql语句.
	 * @param values 命名参数,按名称绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final Page<T> page, final String hql, final Map<String, ?> values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}

		setPageParameterToQuery(q, page);

		List result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按Criteria分页查询.
	 * 
	 * @param page 分页参数.
	 * @param criterions 数量可变的Criterion.
	 * 
	 * @return 分页查询结果.附带结果列表及所有查询输入参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final Page<T> page, final Criterion... criterions) {
		Assert.notNull(page, "page不能为空");

		Criteria c = createCriteria(criterions);

		if (page.isAutoCount()) {
			long totalCount = countCriteriaResult(c);
			page.setTotalCount(totalCount);
		}

		setPageParameterToCriteria(c, page);

		List result = c.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 设置分页参数到Query对象,辅助函数.
	 */
	protected Query setPageParameterToQuery(final Query q, final Page<T> page) {

		Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

		//hibernate的firstResult的序号从0开始
		q.setFirstResult(page.getFirst() - 1);
		q.setMaxResults(page.getPageSize());
		return q;
	}

	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 */
	protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) {

		Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

		//hibernate的firstResult的序号从0开始
		c.setFirstResult(page.getFirst() - 1);
		c.setMaxResults(page.getPageSize());

		if (page.isOrderBySetted()) {
			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(page.getOrder(), ',');

			Assert.isTrue(orderByArray.length == orderArray.length, "分页多重排序参数中,排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (Page.ASC.equals(orderArray[i])) {
					c.addOrder(Order.asc(orderByArray[i]));
				} else {
					c.addOrder(Order.desc(orderByArray[i]));
				}
			}
		}
		return c;
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql, final Object... values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
		}
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql, final Map<String, ?> values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
		}
	}

	private String prepareCountHql(String orgHql) {
		String fromHql = orgHql;
		//select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;
		return countHql;
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	@SuppressWarnings("unchecked")
	protected long countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
			ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		// 执行Count查询
		Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
		long totalCount = (totalCountObject != null) ? totalCountObject : 0;

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		return totalCount;
	}

	//-- 属性过滤条件(PropertyFilter)查询函数 --//

	/**
	 * 按属性查找对象列表,支持多种匹配方式.
	 * 
	 * @param matchType 匹配方式,目前支持的取值见PropertyFilter的MatcheType enum.
	 */
	public List<T> findBy(final String propertyName, final Object value, final MatchType matchType) {
		Criterion criterion = buildCriterion(propertyName, value, matchType);
		return find(criterion);
	}

	/**
	 * 按属性过滤条件列表查找对象列表.
	 */
	public List<T> find(List<PropertyFilter> filters) {
		Criterion[] criterions = buildCriterionByPropertyFilter(filters);
		return find(criterions);
	}

	/**
	 * 按属性过滤条件列表分页查找对象.
	 */
	public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) {
		Criterion[] criterions = buildCriterionByPropertyFilter(filters);
		return findPage(page, criterions);
	}

	/**
	 * 按属性条件参数创建Criterion,辅助函数.
	 */
	protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = null;
		//根据MatchType构造criterion
		switch (matchType) {
		case EQ:
			criterion = Restrictions.eq(propertyName, propertyValue);
			break;
		case LIKE:
			criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
			break;
		case LIKEE:
			criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.EXACT);
			break;	
		case LIKEL:
			criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.START);
			break;	
		case LIKER:
			criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.END);
			break;		
		case NE:
			criterion = Restrictions.ne(propertyName, propertyValue);
			break;
		case LE:
			criterion = Restrictions.le(propertyName, propertyValue);
			break;
		case LT:
			criterion = Restrictions.lt(propertyName, propertyValue);
			break;
		case GE:
			criterion = Restrictions.ge(propertyName, propertyValue);
			break;
		case GT:
			criterion = Restrictions.gt(propertyName, propertyValue);
		}
		return criterion;
	}
	
	/**
	 * 按属性条件参数创建Criterion,辅助函数.
	 */
	protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType, final Collection values) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = null;
		if(StringUtils.contains(propertyName, "$$$")) {//支持关联条件查询
			String[] ss = StringUtils.split(propertyName, "$$$");
			if(ss.length >= 2) {
				String subEntityName = ss[0];
				String[] pnArr = StringUtils.split(ss[1], ".");
				String reEn = pnArr[0];
				String pn = pnArr[1];
				DetachedCriteria subQuery = DetachedCriteria.forEntityName(subEntityName, "mm");
				Criterion subCr = buildCriterion(pn, propertyValue, matchType, values);
				subQuery.add(subCr);
				subQuery.add(Property.forName("mm.id").eqProperty("aa." + reEn + ".id"));
				subQuery.setProjection(Projections.property("mm.id"));
				criterion = Subqueries.exists(subQuery);
			}
		} else {
			//根据MatchType构造criterion
			switch (matchType) {
			case EQ:
				criterion = Restrictions.eq(propertyName, propertyValue);
				break;
			case LIKE:
				criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
				break;
			case LIKEE:
				criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.EXACT);
				break;	
			case LIKEL:
				criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.START);
				break;	
			case LIKER:
				criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.END);
				break;		
			case LE:
				criterion = Restrictions.le(propertyName, propertyValue);
				break;
			case NE:
				criterion = Restrictions.ne(propertyName, propertyValue);
				break;
			case LT:
				criterion = Restrictions.lt(propertyName, propertyValue);
				break;
			case GE:
				criterion = Restrictions.ge(propertyName, propertyValue);
				break;
			case GT:
				criterion = Restrictions.gt(propertyName, propertyValue);
			case IN:
				criterion = Restrictions.in(propertyName, values);
			}
		}
		return criterion;
	}

	/**
	 * 按属性条件列表创建Criterion数组,辅助函数.
	 */
	protected Criterion[] buildCriterionByPropertyFilter(final List<PropertyFilter> filters) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			if (!filter.hasMultiProperties()) { //只有一个属性需要比较的情况.
				Criterion criterion = buildCriterion(filter.getPropertyName(), filter.getMatchValue(), filter
						.getMatchType(), filter.getValues());
				criterionList.add(criterion);
			} else {//包含多个属性需要比较的情况,进行or处理.
				Disjunction disjunction = Restrictions.disjunction();
				for (String param : filter.getPropertyNames()) {
					Criterion criterion = buildCriterion(param, filter.getMatchValue(), filter.getMatchType(), filter.getValues());
					disjunction.add(criterion);
				}
				criterionList.add(disjunction);
			}
		}
		return criterionList.toArray(new Criterion[criterionList.size()]);
	}
	
	/**
	 * Hql分页查询，主要针对复杂多表关联查询
	 * 
	 * @param hql
	 * @param page
	 * @param filters
	 * @return
	 */
	public Page<T> findPage(final String hql, final Page<T> page, final List<PropertyFilter> filters, final Object... values) {
		StringBuffer sb = new StringBuffer(hql);
		List<Object> params = new ArrayList<Object>();
		if(null!=values) {
			for(Object o : values) {
				params.add(o);
			}
		}
		for (PropertyFilter filter : filters) {
			sb.append(" and ");
			if (!filter.hasMultiProperties()) { //只有一个属性需要比较的情况.
				sb.append(buildHqlByPropertyFilter(params, filter.getPropertyName(), filter.getMatchValue(), filter
						.getMatchType(), filter.getValues()));
			} else {//包含多个属性需要比较的情况,进行or处理.
				sb.append("(");
				int i = 0;
				for (String param : filter.getPropertyNames()) {
					if(i++ > 0) {
						sb.append(" or ");
					}
					sb.append(buildHqlByPropertyFilter(params, param, filter.getMatchValue(), filter
							.getMatchType(), filter.getValues())); 
				}
				sb.append(")");
			}
		}
		sb.append(" ");
		//增加排序条件
		sb.append(buildOrderBy(page));
		return this.findPage(page, sb.toString(), params.toArray(new Object[params.size()]));
	}
	
	/**
	 * 生成查询条件语句
	 * 
	 * @param params
	 * @param propertyName
	 * @param propertyValue
	 * @param matchType
	 * @param values
	 * @return
	 */
	protected String buildHqlByPropertyFilter(final List<Object> params, final String propertyName, final Object propertyValue, final MatchType matchType, final Collection<Object> values) {
		StringBuffer sb = new StringBuffer();
		switch (matchType) {
			case EQ:
				sb.append(propertyName);
				sb.append(" = ?");
				params.add(propertyValue);
				break;
			case LIKE:
				sb.append(propertyName);
				sb.append(" like ?");
				params.add("%" + propertyValue + "%");
				break;
			case LIKEE:
				sb.append(propertyName);
				sb.append(" like ?");
				params.add(propertyValue);
				break;
			case LIKEL:
				sb.append(propertyName);
				sb.append(" like ?");
				params.add(propertyValue + "%");
				break;
			case LIKER:
				sb.append(propertyName);
				sb.append(" like ?");
				params.add("%" + propertyValue);
				break;	
			case LE:
				sb.append(propertyName);
				sb.append(" <= ?");
				params.add(propertyValue);
				break;
			case LT:
				sb.append(propertyName);
				sb.append(" < ?");
				params.add(propertyValue);
				break;
			case GE:
				sb.append(propertyName);
				sb.append(" >= ?");
				params.add(propertyValue);
				break;
			case GT:
				sb.append(propertyName);
				sb.append(" > ?");
				params.add(propertyValue);
			case IN:
				sb.append(propertyName);
				sb.append(" in (");
				List<String> strList = new ArrayList<String>();
				for(Object o : values) {
					strList.add("?");
					params.add(o);
				}
				sb.append(StringUtils.join(strList, ","));
				sb.append(")");
		}
		return sb.toString();
	}
	
	/**
	 * 生成排序语句
	 * 
	 * @param page
	 * @return
	 */
	protected String buildOrderBy(final Page<T> page) {
		List<String> orderByList = new ArrayList<String>();
		String orderBy = "";
		//添加分页条件
		if (page.isOrderBySetted()) {
			orderBy = " order by ";
			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(page.getOrder(), ',');
			Assert.isTrue(orderByArray.length == orderArray.length, "分页多重排序参数中,排序字段与排序方向的个数不相等");
			for (int i = 0; i < orderByArray.length; i++) {
				if (Page.ASC.equals(orderArray[i])) {
					orderByList.add(orderByArray[i] + " asc");
				} else {
					orderByList.add(orderByArray[i] + " desc");
				}
			}
		}
		return orderBy + StringUtils.join(orderByList, ",");
	}
	
	/**
	 * 根据sql语句及参数查询指定数量的记录
	 * 
	 * @param sql
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> findDataMapListBySql(String sql,Map<String, Object> param) {
		SQLQuery sq = getSession().createSQLQuery(sql);
		if(null!=param) {
			sq.setProperties(param);
		}
		sq.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return sq.list();
	}
	
	/**
	 * 根据sql语句及参数查询指定数量的记录
	 * 
	 * @param sql
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> findDataMapListBySql(String sql,Map<String, Object> param, Page<Object> page) {
		SQLQuery sq = getSession().createSQLQuery(sql);
		sq.setFirstResult(page.getFirst() - 1);
		sq.setMaxResults(page.getPageSize());
		if(null!=param) {
			sq.setProperties(param);
		}
		sq.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return sq.list();
	}
	
	/**
	 * 查询树形同类编号最大值
	 * @param entityName
	 * @param key
	 * @param pidKey
	 * @param pidKeyVal
	 * @return
	 */
	public String getMaxTreeCode(String entityName, String key, String pidKey, Object pidKeyVal) {
		String hql = "select max(" + key + ") from " + entityName + " where 1=1 ";
		Query ql = null;
		if(pidKeyVal == null) {
			hql = hql + "and " + pidKey + " is null";
			ql = this.createQuery(hql);
		} else {
			hql = hql + "and " + pidKey + " = ?";
			ql = this.createQuery(hql, pidKeyVal);
		}
		ql.setFirstResult(0);
		ql.setMaxResults(1);
		Object obj = ql.uniqueResult();
		return (String)obj;
	}
	
	/**
	 * 获取树形编码
	 * @param entityName
	 * @param key
	 * @param idKey
	 * @param idVal
	 * @return
	 */
	public String getTreeCode(String entityName, String key, String idKey, Object idVal) {
		if(idVal != null) {
			String hql = "select " + key + " from " + entityName + " where " + idKey + " = ? ";
			Query ql = null;
			ql = this.createQuery(hql, idVal);
			ql.setFirstResult(0);
			ql.setMaxResults(1);
			Object obj = ql.uniqueResult();
			return (String)obj;
		} else {
			return null;
		}
	}
	
	/**
	 * 获取树形子编号
	 * @param entityName
	 * @param key
	 * @param parentCode
	 * @param serialNoLen
	 * @param pidKey
	 * @param pidKeyVal
	 * @return
	 */
	public String getAutoTreeCode(String entityName, String key, Integer serialNoLen, String pidKey, Object pidKeyVal, String idKey) {
		String maxNo = this.getMaxTreeCode(entityName, key, pidKey, pidKeyVal);
		StringBuffer sb = new StringBuffer();
		String bVal = StringUtils.defaultString(this.getTreeCode(entityName, key, idKey, pidKeyVal), "");
		sb.append(bVal);
		if(StringUtils.isNotBlank(maxNo)) {
			int start = bVal.length();
			int end = start + serialNoLen;
			String no = StringUtils.substring(maxNo, start, end);
			Integer val = Integer.valueOf(StringUtils.defaultIfEmpty(no, "0")) + 1;
			sb.append(StringUtils.leftPad(String.valueOf(val), serialNoLen, "0"));
		} else {
			sb.append(StringUtils.leftPad("1", serialNoLen, "0"));
		}
		return sb.toString();
	}
	
	/**
	 * 执行sql语句
	 * 
	 * @param sql
	 * @param filters
	 * @return
	 */
	public int execSql(String sql, List<PropertyFilter> filters) {
		Query query = getSession().createSQLQuery(sql);
		if(null!=filters && !filters.isEmpty()) {
			for(PropertyFilter pf : filters) {
				if(pf.getIsInMatchType()) {
					query.setParameterList(pf.getPropertyName(), pf.getValues());
				} else {
					query.setParameter(pf.getPropertyName(), pf.getMatchValue());
				}
			}
		}
		return query.executeUpdate();
	}
	
	/**
	 * 根据查询SQL与参数列表创建Query对象.
	 * 与find()函数可进行更加灵活的操作.
	 * 
	 * @param queryString
	 * @param values   命名参数,按名称绑定.
	 * @return
	 */
	public org.hibernate.query.Query createNativeQuery(final String  queryString,final Object... values){
		Assert.hasText(queryString,"queryString不能为空");
		org.hibernate.query.Query query = getSession().createNativeQuery(queryString);
		if(values !=null){
			for(int i=0;i < values.length; i++) {
				query.setParameter(i+1, values[i]);
			}			
		}
		return query;
	}
	
	/**
	 * 通过原生SQL来查找
	 * @param sql
	 * @param value
	 */
	public List<String> findSingleValueBySQL(String queryString,Object... values){
		org.hibernate.query.Query query = createNativeQuery(queryString, values);
		List<String> resultList = query.getResultList();
		return resultList;
		
	}
	
	/**
	 * 通过原生SQL来查找
	 * @param sql
	 * @param value
	 */
	public List<Object[]> findBySQL(String queryString,Object... values){
		org.hibernate.query.Query query = createNativeQuery(queryString, values);
		List<Object[]> resultList = query.getResultList();
		return resultList;
		
	}
	
}
